import { onBeforeRouteLeave } from "vue-router";
import { useStore as useCacheViewStore } from "@/store/cacheView";
// 跳转特定路由前缓存页面, 字符串数组或'all'，数组即跳转的路由名数组，all代表跳转全部路由
const useCacheWhenTo = (routeNames: string[] | 'all' = []) => {
  const cacheViewStore = useCacheViewStore();
  onBeforeRouteLeave((to, from, next) => {
    let from_name: any = from?.name || '';
    let to_name: any = to?.name || '';
    console.log(from_name)
    if (from.matched.map(x => x.name).includes("index")) {
      cacheViewStore.addCache("index");
    }
    if (from.matched.map(x => x.name).includes("userCenter")) {
      cacheViewStore.addCache("userCenter");
    }
    if (from.matched.map(x => x.name).includes("account")) {
      cacheViewStore.addCache("account");
    }
    if (from_name) {
      if (routeNames === 'all') {
        cacheViewStore.addCache(from_name);
      } else if (routeNames.length > 0) {
        if (routeNames.includes(to_name)) {
          cacheViewStore.addCache(from_name);
        } else {
          cacheViewStore.delCache(from_name);
        }
      }
    }
    console.log(cacheViewStore.cacheView);
    next();
  })
}

export default useCacheWhenTo;